package com.alinesno.cloud.base.boot.web.module.settings;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alinesno.cloud.base.boot.feign.dto.ManagerSourceGenerateDto;
import com.alinesno.cloud.base.boot.feign.facade.ManagerSourceGenerateFeigin;
import com.alinesno.cloud.base.boot.web.utils.GeneratorSourceTool;
import com.alinesno.cloud.base.boot.web.utils.ZipUtils;
import com.alinesno.cloud.common.core.constants.SpringInstanceScope;
import com.alinesno.cloud.common.web.base.advice.TranslateCode;
import com.alinesno.cloud.common.web.base.bean.DatatablesPageBean;
import com.alinesno.cloud.common.web.base.controller.FeignMethodController;
import com.alinesno.cloud.common.web.base.response.ResponseBean;
import com.alinesno.cloud.common.web.base.response.ResponseGenerator;
import com.alinesno.cloud.common.web.login.aop.AccountRecord;
import com.alinesno.cloud.common.web.login.aop.AccountRecord.RecordType;
import com.alinesno.cloud.compoment.generate.Generator;

import cn.hutool.http.HtmlUtil;

/**
 * 代码生成器
 * 
 * @author LuoAnDong
 * @since 2019年4月8日 下午10:29:02
 */
@Controller
@Scope(SpringInstanceScope.PROTOTYPE)
@RequestMapping("boot/platform/source")
public class SourceGenerateController
		extends FeignMethodController<ManagerSourceGenerateDto, ManagerSourceGenerateFeigin> {

	private static final Logger log = LoggerFactory.getLogger(SourceGenerateController.class);

	@Value("${alinesno.compoment.generator.path}")
	private String generatorPath;

	@TranslateCode(value = "[{hasStatus:has_status}]")
	@ResponseBody
	@RequestMapping("/datatables")
	public DatatablesPageBean datatables(HttpServletRequest request, Model model, DatatablesPageBean page) {
		log.debug("page = {}", ToStringBuilder.reflectionToString(page));
		return this.toPage(model, feign, page);
	}

	/**
	 * 保存新对象
	 * 
	 * @param model
	 * @param managerCodeDto
	 * @return
	 * @throws IOException
	 */
	@AccountRecord(type = RecordType.OPERATE_SAVE)
	// @FormToken(remove=true)
	@ResponseBody
	@PostMapping("/generator")
	public ResponseBean generator(Model model, HttpServletRequest request, ManagerSourceGenerateDto dto)
			throws IOException {
		log.debug("generatorPath:{} , dto:{}", generatorPath, ToStringBuilder.reflectionToString(dto));

		Date date = new Date();
		
		//转义DBURL
		dto.setDbUrl(HtmlUtil.unescape(dto.getDbUrl()));

		String downPath = generatorPath + "/" + new SimpleDateFormat("yyyy/MM").format(date) + "/" + dto.getFeignServerPath();
		File f = new File(downPath);

		log.debug("downPath:{}" , downPath);
		
		if (f.exists()) {
			FileUtils.forceDelete(f);
		}
		FileUtils.forceMkdir(f);
		
		Generator g = new GeneratorSourceTool(dto, downPath);
		g.generator(null);
		String targetPath = downPath + "-" + System.currentTimeMillis() + ".zip";
		ZipUtils.toZip(downPath, targetPath, true);

		dto.setFieldProp(targetPath);
		dto = feign.save(dto);
		return ResponseGenerator.ok(dto.getId());
	}

	/**
	 * 下载文件 (分布式部署待优化)
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings("resource")
	@RequestMapping("/downloadCode")
	public ResponseEntity<byte[]> download(HttpServletRequest request, String id) throws IOException {
		
		Optional<ManagerSourceGenerateDto> optional = feign.findById(id) ; 
		
		File file = new File(optional.get().getFieldProp());
		byte[] body = null;
		InputStream is = new FileInputStream(file);
		body = new byte[is.available()];
		is.read(body);
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Disposition", "attchement;filename=" + file.getName());
		HttpStatus statusCode = HttpStatus.OK;
		ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
		return entity;
	}
}
